package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.LitemallAdMapper;
import org.linlinjava.litemall.db.dao.LitemallCompanyMapper;
import org.linlinjava.litemall.db.domain.LitemallAd;
import org.linlinjava.litemall.db.domain.LitemallAdExample;
import org.linlinjava.litemall.db.domain.LitemallCompany;
import org.linlinjava.litemall.db.domain.LitemallCompanyExample;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.List;

@Service
public class LitemallCompanyService {
    @Resource
    private LitemallCompanyMapper companyMapper;

    public List<LitemallCompany> queryIndex() {
        LitemallCompanyExample example = new LitemallCompanyExample();
        example.or().andDeletedEqualTo(false);
        return companyMapper.selectByExample(example);
    }

    public List<LitemallCompany> querySelective(String name, String content, Integer page, Integer limit, String sort, String order) {
        LitemallCompanyExample example = new LitemallCompanyExample();
        LitemallCompanyExample.Criteria criteria = example.createCriteria();

        if (!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        criteria.andDeletedEqualTo(false);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, limit);
        return companyMapper.selectByExample(example);
    }

    public int updateById(LitemallCompany company) {
        company.setUpdateTime(LocalDateTime.now());
        return companyMapper.updateByPrimaryKeySelective(company);
    }

    public void deleteById(Integer id) {
        companyMapper.logicalDeleteByPrimaryKey(id);
    }

    public void add(LitemallCompany company) {
        company.setAddTime(LocalDateTime.now());
        company.setUpdateTime(LocalDateTime.now());
        companyMapper.insertSelective(company);
    }

    public LitemallCompany findById(Integer id) {
        return companyMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询过期的优惠券:
     * 注意：如果timeType=0, 即基于领取时间有效期的优惠券，则优惠券不会过期
     *
     * @return
     */
    public List<LitemallCompany> queryNearyUpdate() {
        LitemallCompanyExample example = new LitemallCompanyExample();
        example.or().andUpdateTimeGreaterThanOrEqualTo(LocalDateTime.now().minus(30, ChronoUnit.MINUTES)).andDeletedEqualTo(false);
        return companyMapper.selectByExample(example);
    }
}
